package com.hwn.datax;

import javafx.application.Application;
import javafx.application.Platform;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ConfigurableApplicationContext;

import java.io.IOException;
import java.net.URL;

public class AppUI extends Application {
    private ConfigurableApplicationContext applicationContext;

    @Override
    public void init() {
        applicationContext = new SpringApplicationBuilder(DataxClientApplication.class).run();
    }

    @Override
    public void start(Stage stage) throws Exception {
        System.out.println("start....");
        Thread.currentThread().setUncaughtExceptionHandler(new DefaultExceptionHandler(stage));

        URL resource = getClass().getClassLoader().getResource("views/main.fxml");
        FXMLLoader fxmlLoader = new FXMLLoader(resource);
        fxmlLoader.setControllerFactory(applicationContext::getBean);
        Scene scene = new Scene(fxmlLoader.load(), 320, 240);
        stage.setScene(scene);
        stage.setWidth(980);
        stage.setHeight(500);
        stage.show();

        applicationContext.publishEvent(new StageReadyEvent(stage));

    }

    @Override
    public void stop() {
        applicationContext.close();
        Platform.exit();
    }

    static class StageReadyEvent extends ApplicationEvent {
        /**
         *
         */
        private static final long serialVersionUID = 1L;

        public StageReadyEvent(Stage stage) {
            super(stage);
        }

        public Stage getStage() {
            // TODO Auto-generated method stub
            return ((Stage) getSource());
        }
    }

    private Parent createRoot() throws IOException {
        FXMLLoader fxmlLoader = new FXMLLoader();
//		System.out.println(ResourceUtils.getURL("main.fxml"));
        /**
         * todo 使用不同的 maven插件 ，打jar包后的文件路径是不同的，需要解决以下这个问题，否则开发环境和打包后的 不一致

         */
        URL url = ClassLoader.getSystemResource("main.fxml");// 打包时用 "BOOT-INF/classes/main.fxml"
        System.out.println(url);
        fxmlLoader.setLocation(url);
        fxmlLoader.setControllerFactory(applicationContext::getBean);
        return fxmlLoader.load();
    }

}
